package cluster

import (
	"context"

	"gitee.com/doraemon1996/bunny/env"
	"gitee.com/doraemon1996/bunny/structure"
)

type cluster struct {
	structure.Control

	// 当前节点ID
	nodeID uint64

	// 通信端点 负责接收远端发来的消息
	local *receiver

	// 远端列表 负责发送消息给远端
	remote map[uint64]*Sender
}

func New() Cluster {
	return new(cluster)
}

func (c *cluster) Init(ctx context.Context, nodeID uint64, cfg *env.NodeConfig) (err error) {
	if nodeID > 0 && (cfg == nil || nodeID != cfg.ID) {
		return ErrInvalidClusterCfg
	}

	c.Control.Init(ctx, func() {
		c.nodeID = nodeID
		c.remote = make(map[uint64]*Sender)
		if nodeID > 0 {
			c.local = new(receiver)
			err = c.local.Init(c.Control.Context(), c, cfg)
		}
	})

	return
}

func (c *cluster) Start() (err error) {
	c.Control.Start(func() {

	})
	return
}
